本文主要介绍
- OutStream常用方法罗列
- OutStream类部分源码
OutputStream提供了3个write()来做数据的输出,这个是和InputStream的read()是相对应的
实现类
几种不同的OutputStream:
- ByteArrayOutputStream
把信息存入内存中的一个缓冲区中 - FileOutputStream
把信息存入文件中 - PipedOutputStream
实现了pipe的概念,主要在线程中使用 - SequenceOutputStream
把多个OutStream合并为一个OutStream
源码
常用方法
方法 | 作用 |
---|---|
public void write(byte b[ ]) |
将参数b中的字节写到输出流 |
public void write(byte b[ ], int off, int len) |
将参数b的从偏移量off开始的len个字节写到输出流 |
public abstract void write(int b) |
先将int转换为byte类型,把低字节写入到输出流中 |
public void flush( ) | 将数据缓冲区中数据全部输出,并清空缓冲区 |
public void close( ) | 关闭输出流并释放与流相关的系统资源 |
定义
1 | package java.io; |
写数据
write(int b)
- 先将int转换为byte类型,把低字节写入到输出流中。此方法丢弃 int 类型高位的 3 个字节,只保留低位的 1 个字节写入
- 抽象方法,没有具体实现,因为子类必须实现此方法的一个实现
- 用法
Writes the specified byte to this output stream. The general contract for
write
is that one byte is written to the output stream. The byte to be written is the eight low-order bits of the argumentb
. The 24 high-order bits ofb
are ignored.
- 代码
1 | public abstract void write(int b) throws IOException; |
write(byte b[])
将参数b中的字节写到输出流
- 用法
Writes
b.length
bytes from the specified byte array to this output stream.
- 代码
1 | public void write(byte b[]) throws IOException { |
write(byte b[], int off, int len)
将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此输出流。
- 用法
Writes
len
bytes from the specified byte array starting at offsetoff
to this output stream.
- 代码
1 | public void write(byte b[], int off, int len) throws IOException { |
flush()
Flushes this output stream and forces any buffered output bytes to be written out.
- 将数据缓冲区中数据全部输出,并清空缓冲区
- 此类未实现具体行为,子类应该复写此方法
1 | public void flush() throws IOException { |
close()
Closes this output stream and releases any system resources associated with this stream.
- 关闭此输出流并释放与此流有关的所有系统资源
- 此类未实现具体行为,子类应该复写此方法
1 | public void close() throws IOException { |